/*

Copyright (C) 2010 Hans-Werner Hilse <hilse@web.de>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

*/

package de.hilses.droidreader;

import java.lang.String;

/**
 * Instantiate this for each PDF document
 */
public class PdfDocument {
	/**
	 * the native MuPDF backend will set this to the document title
	 */
	public String metaTitle;
	/**
	 * backend sets this to the number of pages
	 */
	public int pagecount = 0;

	/**
	 * this will be used to store a C Pointer (ick!) to the
	 * structure holding our references in the native code
	 */
	protected long mHandle = 0;

	/**
	 * will open a PDF document
	 * @param fitzMemory the memory that the MuPDF rendering backend is allowed to claim
	 * @param filename file to be opened
	 * @param password password for the PDF
	 * @return new handle
	 */
	private native long nativeOpen(
			int fitzMemory,
			String filename, String password)
		throws
			PasswordNeededException,
			WrongPasswordException,
			CannotRepairException,
			CannotDecryptXrefException;

	/**
	 * open a PDF
	 * @param filename the PDF file
	 * @param password the password to use for opening
	 */
	public void open(String filename, String password)
	throws
		PasswordNeededException,
		WrongPasswordException,
		CannotRepairException,
		CannotDecryptXrefException
	{
		if(mHandle != 0)
			this.close();
		mHandle = this.nativeOpen(
				PdfRender.fitzMemory, filename, password);
	}

	/**
	 * close a PDF document
	 * @param dochandle the handle that was returned upon opening the PDF
	 */
	private native void nativeClose(long dochandle);

	/**
	 * this cleans up the memory used by this document. The document
	 * cannot be used after calling this!
	 */
	public void close() {
		if(mHandle != 0) {
			this.nativeClose(mHandle);
			mHandle = 0;
			pagecount = 0;
		}
	}

	/**
	 * Find out if the current document is a memory hog.
	 */
	private native int nativeIsMemoryHog(long dochandle);

    public int isMemoryHog() {
        return this.nativeIsMemoryHog(mHandle);
    }

	/**
	 * destructor, cleans up memory
	 */
	public void finalize() {
		this.close();
	}
}
